<?php
namespace backend\controllers;

use common\models\Common;
use common\models\Score;
use common\service\ImgUpdate;
use SohuCS\Scs\Exception\ScsException;
use Yii;
use yii\base\Exception;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use common\models\RegistForm;
use common\models\Student;
use common\models\UpdateForm;
use common\models\SearchForm;
use common\models\AddForm;
use yii\data\ActiveDataProvider;
use yii\web\UploadedFile;
use yii\helpers\Json;
use yii\data\Sort;
use SohuCS\Scs\ScsClient;
/**
 * Site controller
 */
class SiteController extends Controller
{
    public $enableCsrfValidation = false;
    /**
     * @inheritdoc
     * 过滤器
     */
    public function behaviors()
    {
        return [
            //授权
/*            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error', 'regist', 'test'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index', 'delete', 'update',
                            'add', 'filter', 'info', 'upload', 'show'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            //指定请求操作
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    //'logout' => ['post'],
                ],
            ],*/
        ];
    }

    public function actionTest()
    {
        echo date('Ym',time());die;
        try{
            define('SCS_ACCESS_KEY', 'CJHHdlldG5Xa81SiEaVTIA==');
            define('SCS_SECRET_KEY', 'Y9ISSAwPEkn/VGalG3r1lg==');

            // Establish connection with DreamObjects with an Scs client.
            $client = ScsClient::factory(array(
                'key'      => SCS_ACCESS_KEY,
                'secret'   => SCS_SECRET_KEY,
                'region'   => "bjcnc"
            ));

            $bucket='focus-img';
/*            if(!$client->doesBucketExist($bucket)){
                $result = $client->createBucket(array(
                    'Bucket' => $bucket,
                    'LocationConstraint' => 'bjcnc.azure.sohuno.com'
                ));
                $client->waitUntilBucketExists(array('Bucket' => $bucket));
            }*/
            $result = $client->getObject(array(
                'Bucket' => $bucket,
                'Key' => 'data.txt',
                'SaveAs' => 'data.txt '
            ));

/*
            $filename="dianping/photos/".date('Ym',time())."/logo.jpg";
            $pathToFile="/usr/local/nginx/html/project/backend/web/img/logo.png";

            $result = $client->putObject(array(
                'Bucket' => $bucket,
                'Key' => $filename,
                'Body' => fopen($pathToFile,'r+'),
            ));*/
        }catch (ScsException $e){
            print_r($e->getMessage());
        }

        //var_export($client->listBuckets());
/*        $bucket = 'huake1';

        // Get the request ID
        //echo $result['RequestId'] . "\n";

        // Poll the bucket until it is accessible
        */
    }
    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionIndex()
    {
        $this->getView()->title="后台管理系统";
        return $this->render("index");
    }


    public function beforeAction($action)
    {
        $action = Yii::$app->controller->id.'/'.Yii::$app->controller->action->id;

        if(\Yii::$app->user->can($action)){
            return true;
        }else if($action=='site/login' || $action=='site/regist' || $action=='site/error' || $action=='site/logout' || $action=='site/test'){
            return true;
        }else{
            //$id=Yii::$app->user->getId();
            if(!Yii::$app->user->isGuest){
                echo"<script>alert('对不起，您现在还没获此操作的权限');
                    window.location.href='/site/index';</script>";
            }else{
                echo"<script>alert('对不起，您现在还没获此操作的权限');
                    window.location.href='/site/login';</script>";
                //$this->redirect("/site/login");
            }
            //return false;
            //throw new Exception("..");
        }
    }

    public function actionImg()
    {

        //header("Content-Type:image/png");
        Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
        Yii::$app->response->content=Common::createImg();
        Yii::$app->response->headers->set('Content-Type', 'image/png');
        Yii::$app->end();
    }
    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionInfo()
    {

        $this->getView()->title="管理学生";
        $searchForm=Yii::$app->request->get("SearchForm");
        //筛选
        if(isset($searchForm)){
            $username=$searchForm["username"];
            $score=$searchForm["score"];
            $tag=Yii::$app->request->get("tag");


            $query =  Student::filterStudent($username,$score,$tag);
        }else{
            $query =  Student::find()->orderBy('id Desc');

        }
        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 10,
            ],
            'sort'=>new Sort([
                'attributes' => [
                    'id',
                ],
            ]),
        ]);

        $model = $this->actionSearch();
        //print_r(Yii::$app->user->identity);
        return $this->render('info',['model'=>$model,'dataProvider'=>$provider]);
    }

    /**
     * Login action.
     *
     * @return string
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();//非访客，跳转到登录成功页
        }

        $model = new LoginForm();
        if(Yii::$app->request->isPost){
            if ($model->load(Yii::$app->request->post()) && $model->login()) {
                return json_encode(array('status'=>"success"));
            } else {
                $errors=$model->getErrors();
                while(is_array($errors)){
                    $errors=current($errors);
                }
                return json_encode(array('status'=>"error",'error'=>$errors));
            }
        }else{
            return $this->renderPartial('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();
        //var_dump(11);
        return $this->redirect('/site/login');
    }

    /**
     * Regist action
     *
     * @return string
     */
    public function actionRegist()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();//非访客，跳转到登录成功页
        }
        $model = new RegistForm();
        if (Yii::$app->request->isPost) {
            $model->setScenario("regist");
            $model->load(Yii::$app->request->post());
            $model->type=1;
            $id=$model->regist();
            if($id){
                $auth=Yii::$app->authManager;
                $role=$auth->getRole('Admin');
                $auth->assign($role,$id);
                return Json::encode(array(
                    'status'=>'success',
                    'id'=>Yii::$app->controller->id,
                    'action'=>'login'
                ));
            }
            else{
                $errors=$model->getErrors() ;
                while(is_array($errors)){
                    $errors=current($errors);
                }
                return Json::encode(array(
                    'status'=>'fail',
                    'msg'=>$errors,
                ));
            }
            //return $this->goBack();
        } else {
            return $this->renderPartial('regist', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Delete action
     *
     * @return string
     */
    public function actionDelete()
    {
        Student::deleteById(Yii::$app->request->get("id"));
        return "删除成功";
    }

    /**
     * update action
     *
     *
     */
    public function actionUpdate()
    {

        $model=new UpdateForm();

        if (Yii::$app->request->isAjax){

            if($model->load(Yii::$app->request->post())&&$model->validate()){

                $model->photo=Yii::$app->request->post("AddForm")['photo'];
                $model->update();
                //return json_encode($model);
                return json_encode(array('status'=>'success'));
            }else{
                $errors=$model->getErrors() ;
                while(is_array($errors)){
                    $errors=current($errors);
                }
                return json_encode(array('status'=>'fail','error'=>$errors));
            }

        } else {

            $student=new Student();
            $student=Student::findOne(Yii::$app->request->get("id"));
            //$model->reload($student);
            return $this->render('update', [
                'model' => $student,
            ]);
        }
    }

    public function actionAdd()
    {
        $this->getView()->title="添加学生";
        $model=new AddForm();
        $model->setScenario("add");

        if (Yii::$app->request->isPost){
            $model->load(Yii::$app->request->post());
            if($model->validate()){
                //$this->actionUpload($model,'photo');
                $model->add();
                return json_encode(array('status'=>'success'));
            }
            else{
                $errors=$model->getErrors() ;
                while(is_array($errors)){
                    $errors=current($errors);
                }
                return json_encode(array('status'=>'fail','error'=>$errors));
            }
        } else {

            return $this->render('add', [
                'model' => $model,
            ]);
        }
    }

/*    private function actionUpload($model,$name)
    {
        $image = UploadedFile::getInstance($model, $name);
        if($image){
            $ext = $image->getExtension();
            $randName = uniqid() . "." . $ext;
            $path = date('y-m-d',time());
            $rootPath = 'uploads/' . $path . "/";
            if (!file_exists($rootPath)) {
                mkdir($rootPath,0777);
            }
            $image->saveAs($rootPath . $randName);
            $model->photo = $rootPath.$randName;
        }else{
            $model->photo=null;
        }
    }*/

    //上传到cs.sohu.com
    public function actionUpload()
    {
        //return ImgUpdate::uploadToScs($_FILES);
        return ImgUpdate::uploadToLocal($_FILES);

    }

    //上传到本机
/*    public function actionUpload()
    {
        try{
            $file=$_FILES['file']['tmp_name'];
            $magicFile = null;
            $info = finfo_open(FILEINFO_MIME_TYPE, $magicFile);
            //3、图片类型限制，
            if ($info) {
                $result = finfo_file($info, $file);
                finfo_close($info);
            }
            if(!in_array($result,array('image/jpeg','image/png','image/jpg'))){
                throw new Exception("非法上传文件类型");
            }

            $image=UploadedFile::usrLoadFiles();//获取到图片上传类

            //对图片上传的非空判断
            if($image){
                $image=$image['file'];
                $this->checkUpload($image);
                $ext = $image->getExtension();
                $randName = uniqid() . "." . $ext;
                $path = date('y-m-d',time());
                $rootPath = 'uploads/' . $path . "/";
                if (!file_exists($rootPath)) {
                    mkdir($rootPath,0777);
                }
                $image->saveAs($rootPath . $randName);
                $photo = $rootPath.$randName;
                return json_encode(array(
                    'status'=>'success',
                    'msg'=>$photo,
                ));
            }else{
                throw new Exception("图片不能为空");
            }
        }catch(Exception $e){
            return json_encode(array(
                'status'=>'error',
                'msg'=>$e->getMessage(),
            ));
        }
    }*/
    /**
     * @param $image
     * 上传图片检测
     */
    private function checkUpload($image)
    {
        $ext=$image->getExtension();

        //对文件类型判断
        if(!in_array($ext,array('png','jpeg','jpg'))) {
            throw new Exception("上传只能为图片");
        }

        if($image->size>=1024*1024){
            throw new Exception("上传图片太大，不超过1MB");
        }

    }

    /**
     *
     */
    public function actionSearch()
    {
        $model = new SearchForm();


        return $model;

    }

    /**
     * 筛选
     */
    public function actionFilter()
    {
        $username=Yii::$app->request->post("username");
        $score=Yii::$app->request->post("score");


        //print_r($username);
        //print_r($score);
        $query =  Student::filterStudent($username,$score);

        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 10,
            ],

        ]);

        return $this->renderPartial("filter",['dataProvider'=>$provider]);
    }

    /**
     * 学生详情
     */
    public function actionShow()
    {
        $scores=Score::getScoresById(Yii::$app->request->get('id'));
        $stu_info=Student::findOne(Yii::$app->request->get('id'));
        return $this->renderPartial("show",
            ['scores' => $scores,
            'stu_info' => $stu_info]
        );
        //var_dump($stu_info->attributes);
    }
}

